import { Component, OnInit, ViewChild } from '@angular/core';
import { SettingsService } from '../../../core/settings/settings.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { CustomValidators } from 'ng2-validation';
import { AuthService } from '../../../core/auth/auth.service';
import { Router, ActivatedRoute } from '@angular/router';
import { ModalDirective } from 'ngx-bootstrap';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  valForm: FormGroup;
  loginError: any;
  @ViewChild('agreementModal') public nodeModal: ModalDirective;
  constructor(public settings: SettingsService, fb: FormBuilder, private authService: AuthService,
    private route: ActivatedRoute, private router: Router) {
    this.loginError = this.route.snapshot.params['loginError'];
    this.valForm = fb.group({
      'account': [null, Validators.compose([Validators.required])],
      'pwd': [null, Validators.required]
    });

  }
  clickAgreement(): void {
    if (this.nodeModal) {
      this.nodeModal.show();
    }
  }
  submitForm($ev, value: any) {
    $ev.preventDefault();
    for (let c in this.valForm.controls) {
      if (this.valForm.controls.hasOwnProperty(c)) {
        this.valForm.controls[c].markAsTouched();
      }
    }
    if (this.valForm.valid) {
      this.authService.login(value).then((data: any) => {
        if (data.code === '0000') {
          if (data.initResult) {
            this.router.navigate(['/']);
          }
        } else {
          this.loginError = data.message;
        }
      });
    }
  }

  ngOnInit() {

  }

}
